import React, { Component } from 'react';
import {
  Button,
  DeviceEventEmitter,
  Dimensions,
  FlatList,
  Image,
  ImageBackground,
  SafeAreaView,
  ScrollView,
  StatusBar,
  StyleSheet,
  Text,
  ToastAndroid,
  TouchableOpacity,
  View,
} from 'react-native';
import UserIcon from '../../compenent/UserIconList';
import UserIconList from '../../compenent/UserIconList';
import { style } from '../../../theme.js';
import { DOMAIN_URL, eventApplyList, lessonDelete, lessonDetail, lessonScoreAdd, userRead, userUnread } from '../../../util/api';
import Icon from 'react-native-vector-icons/MaterialIcons';
import { Dialog, Paragraph, Portal, Provider } from 'react-native-paper';
import { PAGENAME } from '../../../util/PageName';
import moment from "moment";
import RNFS from "react-native-fs";
import FileViewer from "react-native-file-viewer";
import Loading from '../../compenent/Loading';
import ListFooter from '../../compenent/ListFooter';

// const url =
//   "https://521github.com/vinzscam/react-native-file-viewer/raw/master/docs/react-native-file-viewer-certificate.pdf";

// *IMPORTANT*: The correct file extension is always required.
// You might encounter issues if the file's extension isn't included
// or if it doesn't match the mime type of the file.
// https://stackoverflow.com/a/47767860



const { width, height } = Dimensions.get('screen');

class LessonDetailScreen extends Component {

  constructor(props: any) {
    super(props);
    console.log('load detail ', props.route.params.data);

    this.state = {
      data: props.route.params.data,
      visible: false,
      isAdmin: global.USER.isadmin,
      applies: [],
      joinUser: [],
      unjoinUser: [],
      loading: false,
    };

    this.timer = 0
  }
  componentDidMount() {
    this.subscription = this.props.navigation.addListener('focus', () => {
      // do something
      console.log('lesson detail');
      this.loadDataDetail()
      setTimeout(() => {
        // 回来之后如果没有加分就清除定时器
        this.timer && clearTimeout(this.timer)
      }, 1000);
    });
    // console.log('add emit ,', this.subscription);
  }
  getUrlExtension = (url: string) => {
    return url.split(/[#?]/)[0].split(".").pop().trim();
  }
  componentWillUnmount() {
    // Remove the event listener
    this.subscription()
  }

  loadDataDetail = () => {
    lessonDetail(this.state.data.id).then(res => {
      console.log('lessonDetail ', res);
      this.setState({
        data: res.data
      })
    })
    // eventApplyList(this.state.data.id, 1, 1000).then(res => {
    //   console.log('lessonApplyList ', res);
    //   if (res.code == 0) {
    //     this.setState({
    //       applies: res.data
    //     })
    //   }
    // })
    userUnread(this.state.data.id).then(res => {
      console.log('lessonUnjoin ', res);
      this.setState({
        unjoinUser: res.data,
      })
    })
    userRead(this.state.data.id).then(res => {
      console.log('lessonJoin ', res);
      this.setState({
        joinUser: res.data,
      })
    })
  }
  openFile = (path: string) => {
    this.setState({
      loading: false
    })
    FileViewer.open(path).then(() => {
      console.log('view success');
      this.timer = setTimeout(() => {
        console.log('加分啦');
        lessonScoreAdd(this.state.data.id).then((res) => {
          if (res.code == 0) {
            ToastAndroid.show('课程学习加分成功！', 2000)
          } else {
            ToastAndroid.show(`课程学习加分失败:${res.msg}`, 2000)
          }
        }).catch(err => {
          ToastAndroid.show(`课程学习加分失败:${err}`, 2000)
        })
      }, 1 * 60 * 1000);
    }).catch(err => {
      console.error('view error', err);
      this.timer && clearTimeout(this.timer)
    })
  }
  listHeader = () => {
    const { data } = this.state
    console.log('data.attachmentDetail?.type', data.attachmentDetail?.type);
    console.log('global.FILE_TYPE_STRING[data.attachmentDetail?.type]', global.FILE_TYPE_STRING[data.attachmentDetail?.type]);

    return <View>
      <Text style={style.pageTitle}>{data.name}</Text>
      <View style={{ flexDirection: 'row', alignItems: 'center' }}>
        <View style={{ flexDirection: 'row' }}>
          <Icon name={'grade'} size={18} color={'red'} />
          <Text style={{ color: 'rgba(255,0,0,0.5)', marginLeft: 2, fontSize: 16 }}>{data.score}</Text>
        </View>
        <View style={{ flexDirection: 'row', marginLeft: 6 }}>
          <Icon name={'access-time'} size={18} color={'red'} />
          <Text
            style={{
              color: 'rgba(255,0,0,0.5)',
              marginLeft: 2,
            }}>
            {moment(data.createTime).format('YYYY-MM-DD')}
          </Text>
          <Text>-</Text>
          <Text style={{ color: 'rgba(255,0,0,0.5)', marginLeft: 2 }}>
            {moment(data.endTime).format('YYYY-MM-DD')}
          </Text>
        </View>
      </View>
      {this.state.isAdmin && <View style={{ flexDirection: 'row', marginTop: 8 }}>
        <View style={{ width: 50, height: 35, }}>
          <Button title={'编辑'} onPress={() => {
            this.props.navigation.push(PAGENAME.LESSON_EDIT, { data: data })
          }} />
        </View>
        <View style={{ width: 50, height: 35, marginLeft: 8 }}>
          <Button title={'删除'} onPress={() => {
            this.setState({
              visible: true
            })
          }} />
        </View>
      </View>}
      <Text style={{ marginVertical: 16 }}>课程类型：{global.FILE_TYPE_STRING[data.attachmentDetail?.type]}</Text>
      <Text style={{ marginVertical: 16 }}>{data.description}</Text>

      <View
        style={{
          justifyContent: 'center',
          alignContent: 'center',
          marginVertical: 30,
        }}>
        <Loading loading={this.state.loading} />

        <View style={style.pageButton}>
          {data.available ? <Button
            title={'学习课程'}
            onPress={() => {
              // "attachmentDetail":
              console.log('get lesson ', data);
              // "attachmentDetail":
              const url = `${DOMAIN_URL}${data.attachmentDetail.path}`
              const extension = this.getUrlExtension(url);
              this.setState({
                loading: true
              })
              // Feel free to change main path according to your requirements.
              const localFile = `${RNFS.DocumentDirectoryPath}/${data.id}.${extension}`;
              RNFS.exists(localFile)
                .then(exists => {
                  if (exists) {
                    this.openFile(localFile)
                  } else {
                    const options = {
                      fromUrl: url,
                      toFile: localFile,
                    };
                    RNFS.downloadFile(options).promise
                      .then(() => {
                        console.log('download success!');
                        this.openFile(localFile)
                      })
                      .catch((error) => {
                        ToastAndroid.show('打开文件失败' + error, 2000)
                        this.setState({
                          loading: false
                        })
                      });
                  }
                })
            }}
          /> : <Button
            title={'活动已结束'}
            disabled={true}
            onPress={() => {
            }}
          />}
        </View>
      </View>
      {this.state.isAdmin && (
          <View>
            <Text style={style.subTitle}>参与党员</Text>
            <UserIconList users={this.state.joinUser} />
            <Text style={style.subTitle}>未参与党员</Text>
            <UserIconList users={this.state.unjoinUser} />
          </View>
      )}

    </View>
  }
  listSep = () => {
    return <View style={{
      height: 1, // 分割线的高度
      width: '100%', // 分割线的宽度，这里设置为100%使其充满整个容器宽度
      backgroundColor: 'rgb(246, 150, 150)', // 分割线的颜色
      marginVertical: 6, // 分割线上下的外边距，可以根据需要调整
    }}></View>
  }
  deleteActive = () => {
    lessonDelete(this.state.data.id).then(res => {
      if (res.code == 0) {
        ToastAndroid.show('删除成功', 2000)
        this.setState({
          visible: false
        })
        this.props.navigation.goBack({ refresh: true });
        // DeviceEventEmitter.emit(PAGENAME.ACTIVE, { name: 'back' });
      } else {
        ToastAndroid.show(`删除失败:${res.msg}`, 2000)
      }
    })
  }
  render() {
    return (
      <Provider>
        <View>
          <Portal>
            <Dialog visible={this.state.visible} onDismiss={() => {
              this.setState({
                visible: false
              })
            }}>
              <Dialog.Title>确认删除数据</Dialog.Title>
              <Dialog.Content>
                <Paragraph>确认删除：{this.state.data.name}</Paragraph>
              </Dialog.Content>
              <Dialog.Actions>
                <View style={{ width: 100 }}>
                  <Button title={'删除'} color={'red'} onPress={this.deleteActive} />
                </View>
                <View style={{ marginLeft: 8, width: 100 }}>
                  <Button title={'取消'} onPress={() => {
                    this.setState({
                      visible: false
                    })
                  }} />
                </View>


              </Dialog.Actions>
            </Dialog>
          </Portal>
        </View>
        <ScrollView style={styles.container}>
          {this.listHeader()}
          <ListFooter />
        </ScrollView >
      </Provider>

      // </ImageBackground>
    );
  }
  emptyApply = () => {
    return <View style={{ justifyContent: 'center', alignItems: 'center', margin: 8 }}>
      {/* <Text>暂无申请</Text> */}
    </View>
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    marginHorizontal: 8,
    marginTop: 8,
  },
  indexDataRow: {
    marginBottom: 4,
    flexDirection: 'row',
    // justifyContent: 'space-between',
  },
});

export default LessonDetailScreen;
